using System;
using UnityEngine;
using System.IO;
using JetBrains.Rider.Unity.Editor;
using Puerts;
using UnityEditor;

[CustomEditor(typeof(TypeScript))]
public class PythonScriptAssetInspector:Editor{
	private const int kMaxChars = 7000;
	private GUIStyle m_TextStyle;
	private TypeScript textAsset;
	string text = "";
	private void OnEnable()
	{
		if (base.targets.Length == 1)
		{
			textAsset = this.target as TypeScript;
			
			string js = getJsPath(textAsset);
			string ts = getTsPath(textAsset);
			if(File.Exists(js))
			{
				text = File.ReadAllText(js);
				if (!textAsset.m_compiled)
				{
					textAsset.m_compiled = true;
					EditorUtility.SetDirty(this.target);
				}
			}
			else
			{
				if(File.Exists(ts))
					text = File.ReadAllText(ts);
				else
				{
					text = "...";
				}
			}
			if (text.Length > 2000)
			{
				text = text.Substring(0, 2000) + @"...
						<...etc...>";
			}
		}
	}

	private void OnDisable()
	{
		text = null;
	}

	public override void OnInspectorGUI ()
	{
		if (this.m_TextStyle == null) {
			this.m_TextStyle = "ScriptText";
		}
		bool enabled = GUI.enabled;
		GUI.enabled = true;
		if (textAsset != null) {
			Rect rect = GUILayoutUtility.GetRect (new GUIContent(text), this.m_TextStyle);
			rect.x = 0;
			rect.y -= 3;
			rect.width += 17;
			GUI.Box (rect, text, this.m_TextStyle);
			//button
			GUILayout.BeginHorizontal();
			if (Application.isPlaying && textAsset.m_compiled)
			{
				if (GUILayout.Button("Require"))
					RequireFile(textAsset);
				if (GUILayout.Button("Eval"))
					ExcuteFile(textAsset);
			}
			GUILayout.EndHorizontal();
			GUILayout.BeginHorizontal();

			if (GUILayout.Button("Edit (Ts)"))
				AssetDatabase.OpenAsset(textAsset);
			if (textAsset.m_compiled && GUILayout.Button("Edit (Js)"))
			{
#if UNITY_2018_1_OR_NEWER
				TypeScriptOpenAsset.OpenFileDllImplementation(getJsPath(textAsset), 0, 0);
#else
				Packages.Rider.Editor.EditorPluginInterop.OpenFileDllImplementation(getJsPath(textAsset),0,0);
#endif
			}
			GUILayout.EndHorizontal();
		}
		GUI.enabled = enabled;
	}

	void RequireFile(TypeScript textAsset)
	{
		JsManager.Instance.GetJsEnv().Eval($"require('{textAsset.module}').init()");
	}
	void ExcuteFile(TypeScript textAsset)
	{
		string js = getJsPath(textAsset);
		string text = File.ReadAllText(js);
		JsManager.Instance.GetJsEnv().Eval(text);
	}

	string getJsPath(TypeScript ts)
	{
		return JsLoader.PathJs + ($"{ts.module}.js");
	}
	string getTsPath(TypeScript ts)
	{
		return JsLoader.PathTs + ($"{ts.module}.ts");
	}
}